<template>
  <t-modal
    :title="operateType == 1 ? '新增标记' : '编辑标记'"
    :width="900"
    :visible="visible"
    wrapClassName="add-btm-viewport-modal"
    @cancel="handleCancel()"
  >
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <!-- 标记名称 -->
      <a-form-model-item ref="name" label="标记名称" prop="name">
        <a-input v-model="form.name" placeholder="请输入标记名称" />
      </a-form-model-item>
      <!-- 标记类型 -->
      <a-form-model-item
        ref="type"
        label="标记类型"
        prop="type"
        class="marker-type-item"
      >
        <a-select
          v-model="form.type"
          placeholder="请选择标记类型"
          :loading="loading"
        >
          <a-select-option
            :value="item.dicItemCode"
            v-for="item in typeSource"
            :key="item.dicItemCode"
          >
            {{ item.dicItemName }}
          </a-select-option>
        </a-select>
        <div class="type-icon" :class="getJBClassName(form.type)"></div>
      </a-form-model-item>
      <!-- 关联BIM -->
      <a-form-model-item ref="bimId" label="关联BIM" prop="bimId">
        <div class="about-bim">
          {{ form.bimId }}
          <div
            class="reassociation-btn"
            v-if="operateType == 2"
            @click="reChoose()"
          >
            重新关联
          </div>
        </div>
      </a-form-model-item>
      <!-- 参与人员 -->
      <a-form-model-item ref="people" label="参与人员" prop="people">
        <personnel-popup
          v-model="form.people"
          placeholder="请选择参与人员"
          :multiple="true"
          :url="
            '/probusiness/bimMarkMain/getTreeOrganizationAndUserDataByOrgCode?orgCode=' +
              currentProject().orgCode
          "
        ></personnel-popup>
      </a-form-model-item>
      <!-- 标记描述 -->
      <a-form-model-item ref="desc" label="标记描述" prop="desc">
        <a-input
          v-model="form.desc"
          type="textarea"
          placeholder="请输入标记描述"
        />
      </a-form-model-item>
    </a-form-model>
    <template slot="footer">
      <a-button @click="handleCancel()">取消</a-button>
      <a-button type="primary" @click="handleOk()" :loading="submitLoading">
        确定
      </a-button>
    </template>
  </t-modal>
</template>
<script>
//新增标记【弹窗】
import { axios } from "@/utils/request";
import { PersonnelPopup } from "@/components";
import { getDicItemByCode } from "@/api/common.js";
export default {
  inject: ["currentProject", "sceneSource"],
  props: {
    operateType: {
      type: Number,
      default: 1,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    probeRet: {
      type: Object,
      default: () => {},
    },
    /////
    viewportData: {
      type: Object,
      default: () => {},
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          let { operateType } = this;
          this.getTypeData();
          if (operateType == 2) {
            //编辑
            let {
              markName,
              markType,
              componentId,
              markDesc,
              userNameIdLs,
            } = this.viewportData;
            this.form.name = markName;
            this.form.type = markType;
            this.form.bimId = componentId;
            this.form.desc = markDesc;
            this.form.people = (userNameIdLs ?? []).toString();
          } else {
            this.snapshot = "";
            this.form.name = "";
            this.form.type = undefined;
            this.form.desc = "";
            this.form.people = "";
          }
          this.getViewportSnapshot();
        }
      },
      immediate: true,
    },
    probeRet: {
      handler(val) {
        let { elemId } = val;
        this.form.bimId = elemId;
      },
    },
  },
  components: {
    PersonnelPopup,
  },
  data() {
    return {
      reChooseFlag: false,
      typeSource: [],
      loading: false,
      submitLoading: false,
      snapshot: "",
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      form: {
        name: "",
        type: undefined,
        bimId: "",
        people: "",
        desc: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入标记名称",
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择标记类型",
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted() {},
  methods: {
    //查询标记类型列表
    getTypeData() {
      return new Promise((resolve, reject) => {
        this.loading = true;
        getDicItemByCode({ code: "MarkType" })
          .then((res) => {
            let { data } = res;
            this.typeSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.typeSource = [];
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //图标样式
    getJBClassName(type = "") {
      switch (type) {
        //设计问题
        case "MarkType.01":
          return "sj";

        //施工问题
        case "MarkType.02":
          return "sg";

        //安全问题
        case "MarkType.03":
          return "aq";

        //质量问题
        case "MarkType.04":
          return "zl";

        //其他问题
        case "MarkType.05":
          return "qt";

        default:
          break;
      }
    },

    //获取视口快照
    getViewportSnapshot() {
      const canvas = document.getElementById("blackHoleCanvas");
      if (canvas) {
        const context = canvas.getContext("2d");
        const dataUrl = canvas.toDataURL();
        this.snapshot = dataUrl;
      }
    },

    handleOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.operateType == 1) {
            this.addSave();
          } else {
            this.editSave();
          }
        } else {
          return false;
        }
      });
    },

    //编辑
    editSave() {
      let { uuid, remark } = this.viewportData;
      let { orgCode, foreignUuid } = this.currentProject();
      let { sceneId } = this.sceneSource();
      let { dataSetId, elemId, elemPos } = this.probeRet;
      let { name, type, desc, people } = this.form;
      let { snapshot, reChooseFlag } = this;
      let { camDir, camPos, camRotate } = BlackHole3D.Camera.getCamLocate();
      axios
        .post(
          "/probusiness/bimMarkMain/update",
          {
            uuid,
            sceneId,
            proCode: orgCode,
            projid: foreignUuid,
            datasetid: dataSetId,
            componentId: elemId,
            markName: name,
            markDesc: desc,
            markType: type,
            camRotate: JSON.stringify(camRotate),
            camPos: JSON.stringify(camPos),
            camDir: JSON.stringify(camDir),
            userNameIdLs: people.split(","),
            markImage: snapshot,
            remark: reChooseFlag ? JSON.stringify(elemPos) : remark,
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { statusCode } = res;
          if (statusCode == 200) {
            this.$message.success(`编辑成功！`);
            this.$parent.getData();
            this.handleCancel();
          } else {
            this.$message.error(`编辑失败，请稍后重试！`);
          }
        })
        .finally((_) => {
          this.reChooseFlag = false;
          this.submitLoading = false;
        });
    },

    //新增保存
    addSave() {
      let { sceneId } = this.sceneSource();
      let { orgCode, foreignUuid } = this.currentProject();
      let { dataSetId, elemId, elemPos } = this.probeRet;
      let { name, type, desc, people } = this.form;
      let { snapshot } = this;
      let { camDir, camPos, camRotate } = BlackHole3D.Camera.getCamLocate();
      axios
        .post(
          "/probusiness/bimMarkMain/save",
          {
            sceneId,
            proCode: orgCode,
            projid: foreignUuid,
            datasetid: dataSetId,
            componentId: elemId,
            markName: name,
            markDesc: desc,
            markType: type,
            camRotate: JSON.stringify(camRotate),
            camPos: JSON.stringify(camPos),
            camDir: JSON.stringify(camDir),
            userNameIdLs: people.split(","),
            markImage: snapshot,
            remark: JSON.stringify(elemPos),
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { statusCode } = res;
          if (statusCode == 200) {
            this.$message.success(`新增成功！`);
            this.$parent.getData();
            this.handleCancel();
          } else {
            this.$message.error(`新增失败，请稍后重试！`);
          }
        })
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    //重新关联
    reChoose() {
      this.$emit("update:visible", false);
      this.$parent.addOperate = true;
      this.reChooseFlag = true;
    },

    handleCancel() {
      this.snapshot = "";
      this.form.name = "";
      this.form.type = undefined;
      this.form.desc = "";
      this.form.people = "";
      this.$refs.ruleForm.resetFields();
      this.$parent.addOperate = false;
      this.$emit("update:visible", false);
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.add-btm-viewport-modal {
  .marker-type-item {
    .ant-form-item-children {
      position: relative;
      .type-icon {
        position: absolute;
        top: -6px;
        right: -40px;
        width: 26px;
        height: 32px;
        //设计问题
        &.sj {
          background: url("../images/sj.png") no-repeat;
          background-size: 100% 100%;
        }
        //施工问题
        &.sg {
          background: url("../images/sg.png") no-repeat;
          background-size: 100% 100%;
        }
        //安全问题
        &.aq {
          background: url("../images/aq.png") no-repeat;
          background-size: 100% 100%;
        }
        //质量问题
        &.zl {
          background: url("../images/zl.png") no-repeat;
          background-size: 100% 100%;
        }
        //其他问题
        &.qt {
          background: url("../images/qt.png") no-repeat;
          background-size: 100% 100%;
        }
      }
    }
  }
  .about-bim {
    background: #fff;
    height: 32px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    padding: 0 11px;
    display: flex;
    align-items: center;
    color: rgba(0, 0, 0, 0.65);
    font-size: 14px;
    margin-top: 3px;
    position: relative;
    .reassociation-btn {
      position: absolute;
      color: #1677ff;
      cursor: pointer;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
    }
  }
}
</style>
